package com.renli.shiro.realm;

import com.renli.pojo.Login;
import com.renli.pojo.Role;
import com.renli.service.LoginService;
import com.renli.service.RoleService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class LoginRealm2 extends AuthorizingRealm {

    @Autowired
    private LoginService loginService;
    @Autowired
    private RoleService roleService;

    /**
     * 通过角色控制权限
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权2222");
        Login login =(Login) principalCollection.getPrimaryPrincipal();
        List<Role> roleList = roleService.findByLoginId(login.getId());
        Set<String> roleSet = new HashSet<>();

        roleList.forEach(role -> {
            roleSet.add(role.getName());
        });

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleSet);

        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("renzehn22222");
        UsernamePasswordToken token=(UsernamePasswordToken)authenticationToken;
        String username = token.getUsername();
        Login login = loginService.findByName(username);
        // 、如果用户不存在，可以抛出unknownaccountexception
        if (login==null){
            return null;//抛出异常 unknownaccountexception
        }

        ByteSource salt = ByteSource.Util.bytes(login.getUsername());
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(login,login.getPassword(),salt,getName());
        return info;
    }
}
